package com.seeyon.apps.kk.manager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.Strings;

public abstract class AdapterSyncDataManager {
	
	private static final Log log = LogFactory.getLog(AdapterSyncDataManager.class);
	protected FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
	protected FormDataBaseManager formDataBaseManager = (FormDataBaseManager) AppContext.getBean("kkBaseFormManager");
	
	/***
	 * 是否启用
	 * 默认getFormCode()、getSendUser()不为空,启用
	 * @return false ----> 停用
	 */
	public boolean enable(){
		if(Strings.isEmpty(getFormCode())
				|| Strings.isEmpty(getSendUser())){
			return false;
		}
		return true;
	}
	/**
	 * 是否保存数据到无流程表单
	 * 目前只支持同无流程表单
	 * @return 
	 * 是 --> true 
	 * 发起协同 --> false
	 */
	public abstract boolean isUnflow();
	
	/**
	 * 返回保存数据的无流程表单、发起协同表单的模版编号
	 * @return
	 */
	public abstract String getFormCode();
	
	/**
	 * 返回发起人账号
	 * @return
	 */
	public abstract String getSendUser();
	
	/**
	 * 新增修改前删除表单的数据
	 * @return
	 */
	public abstract void delHistoryData();
	
	/**
	 * 获取到同步数据list
	 * @return
	 */
	public abstract List<Map> getSyncData();
	
	/**
	 * 将第三数据转换为表单的Map对象
	 * @param params
	 * @return 表单的Map对象
	 * map 的key值为:
	 * 1	主表单控件的名称
	 * 2	从表为从表名称,value为List<Map>
	 * 3	从表value的Map的key为从表控件名称
	 */
	public abstract Map<String, Object> data2FormMap(Map params);
	
	/**
	 * 校验数据新增设置
	 * @return 
	 * 1、只校验主表返回表单控件名称,多个控件以","分隔,
	 * 2、校验从表数据返回Map对象
	 * 	map.add("main", 表单控件名称,多个控件以","分隔)
	 *  map.add(从表名称，从表控件名称,多个控件以","分隔)
	 * 3、返回空直接新增
	 */
	public abstract Object vaildateDataUnique();
	
	
	/**
	 * 根据校验数据新增逻辑,新增或者修改底表数据
	 * @param 表单的Map对象
	 * map 的key值为:
	 * 1	主表单控件的名称
	 * 2	从表为从表名称,value为List<Map>
	 * 3	从表value的Map的key为从表控件名称
	 * @return
	 * @throws Exception
	 */
	public int saveOrUpdateData(Map<String, Object> params) throws Exception{
		FormBean bean = formApi4Cap4.getFormByFormCode(getFormCode());
		FormDataMasterBean formDataMasterBean = null;
		boolean isMainAdd = false;
		Object unique = vaildateDataUnique();
		if(unique == null){
			isMainAdd = true;
		} else if(unique instanceof String
				|| unique instanceof Map){
			Map<String, Object> vmap = new HashMap<String, Object>();
			String fields = null;
			if(unique instanceof Map){
				fields = ((Map) unique).get("main").toString();
			} else {
				fields = unique.toString();
			}
			for(String fieldDisplay: fields.split(",")){
				FormFieldBean field = bean.getFieldBeanByDisplay(fieldDisplay);
				if(field != null && field.isMasterField()){
					formDataBaseManager.change2Map(field, params.get(fieldDisplay), vmap);
				}
			}
			if(vmap.isEmpty()){
				isMainAdd = true;
			} else {
				FlipInfo flipInfo = new FlipInfo(1, 200);
				List<FormDataMasterBean> masterDataList = formApi4Cap4.findMasterDataList(flipInfo, bean.getId(), null, vmap);
				if(CollectionUtils.isNotEmpty(masterDataList)){
					isMainAdd = true;
					for(FormDataMasterBean dataMaster: masterDataList){
						boolean isUnique = false;
						for(String fieldName: vmap.keySet()){
							if(vmap.get(fieldName) == null
									&& dataMaster.getFieldValue(fieldName) == null){
								isUnique = true;
							} else if(vmap.get(fieldName) != null 
									&&vmap.get(fieldName).equals(dataMaster.getFieldValue(fieldName))){
								isUnique = true;
							} else {
								isUnique = false;
								break;
							}
						}
						if(isUnique){
							isMainAdd = false;
							formDataMasterBean = formApi4Cap4.findDataById(dataMaster.getId(), bean, null);
							break;
						}
					}
				} else {
					isMainAdd = true;
				}
			}
		} else {
			isMainAdd = true;
		}
		
		if(isMainAdd){
			try{
				formDataBaseManager.saveUnflowData(getFormCode(), getSendUser(), params);
				return 1;//新增成功
			} catch(Exception e){
				log.error("##客开日志: ", e);
				return 0;//新增失败
			}
		} else {
			String ret = "";
			try{
				if(unique instanceof Map){
					((Map)unique).remove("main");
					ret = formDataBaseManager.updateFormData(getFormCode(), formDataMasterBean, params, (Map)unique);
				} else {
					ret = formDataBaseManager.updateFormData(getFormCode(), formDataMasterBean, params, null);
				}
			} catch(Exception e){
				log.error("##客开日志: ", e);
				return 2;//更新失败
			}
			if(Strings.isEmpty(ret)){
				return 3;//未更新
			} else {
				return 4;//更新成功
			}
		}
	}
	
}
